iT邦幫忙

2023 iThome 鐵人賽

DAY 23
0
Mobile Development

iOS 菜雞的開發日記系列 第 23

鐵人賽 [Day 23] FCM(Firebase Cloud Message) 推播教學(1)

  • 分享至 

  • xImage
  •  

大家好!今天要來教大家怎麼使用 Firebase 進行遠端推播的功能!
在這之前,大家可以先去看一下之前我的鐵人賽文章,先去進行遠端推播的憑證設定,以及 Firebase 專案的建立喔!

遠端推播通知教學連結

Firebase 建立專案與連結自己的 App 教學

正文開始~~

新增 App Library 裡的 FirebaseMessage

https://ithelp.ithome.com.tw/upload/images/20231008/20151391281s9dDcIF.png

勾選 FirebaseMessage 再按下 Add

https://ithelp.ithome.com.tw/upload/images/20231008/20151391U0qn9nyLXN.png

設定 Firebase 的 Cloud Messaging

這邊假設你已經有對 App 進行 Firebase 相關設定了

點選專案設定

https://ithelp.ithome.com.tw/upload/images/20231008/20151391sfxw6FKNaB.png

點選雲端通訊

https://ithelp.ithome.com.tw/upload/images/20231008/20151391StPkej7t8y.png

點選上傳

https://ithelp.ithome.com.tw/upload/images/20231008/20151391W3F2mD4DBf.png

請上傳:

1. 遠端推播的 .p8 憑證

2. 輸入 .p8 憑證 ID

3. 輸入團隊 ID

https://ithelp.ithome.com.tw/upload/images/20231008/20151391dIhJfkdrz8.png

設定 AppDelegate

註冊遠程通知

這段請貼到 didFinishLaunchingWithOptions

UNUserNotificationCenter.current().delegate = self

let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
  options: authOptions,
  completionHandler: { _, _ in }
)

application.registerForRemoteNotifications()

貼完會長這樣:

https://ithelp.ithome.com.tw/upload/images/20231008/20151391ePERwJ2v8q.png

若 delegate 有報錯,請記得新增 Delegate

如下圖:
https://ithelp.ithome.com.tw/upload/images/20231008/20151391w3pDWMTBak.png

import FirebaseMessaging

import FirebaseMessaging

如下圖:
https://ithelp.ithome.com.tw/upload/images/20231008/20151391nKLmDErbBf.png

訪問註冊令牌

給定 Message 的 Delegate 在 didFinishLaunchingWithOptions

Messaging.messaging().delegate = self

如下圖:
https://ithelp.ithome.com.tw/upload/images/20231008/20151391RKZ0zO7BxO.png

記得也要新增 Message 的代理喔!

如下圖:
https://ithelp.ithome.com.tw/upload/images/20231008/201513917HUNZqfdIt.png

獲取當前註冊令牌

在 Message 的 Delegate 裡新增這段程式碼

func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
  print("Firebase registration token: \(String(describing: fcmToken))")

  let dataDict: [String: String] = ["token": fcmToken ?? ""]
  NotificationCenter.default.post(
    name: Notification.Name("FCMToken"),
    object: nil,
    userInfo: dataDict
  )
  // TODO: If necessary send token to application server.
  // Note: This callback is fired at each app startup and whenever a new token is generated.
}

如下圖:

https://ithelp.ithome.com.tw/upload/images/20231008/20151391NUQRu17j4U.png

在 Apple 應用程式中接收訊息(處理通知)

新增下面這段 Code 到 UNUserNotificationCenter 的 Delegate

extension AppDelegate: UNUserNotificationCenterDelegate {
  // Receive displayed notifications for iOS 10 devices.
  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              willPresent notification: UNNotification) async
    -> UNNotificationPresentationOptions {
    let userInfo = notification.request.content.userInfo

    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // Messaging.messaging().appDidReceiveMessage(userInfo)

    // ...

    // Print full message.
    print(userInfo)

    // Change this to your preferred presentation option
    return [[.alert, .sound]]
  }

  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              didReceive response: UNNotificationResponse) async {
    let userInfo = response.notification.request.content.userInfo

    // ...

    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // Messaging.messaging().appDidReceiveMessage(userInfo)

    // Print full message.
    print(userInfo)
  }
}

如下圖:
https://ithelp.ithome.com.tw/upload/images/20231008/20151391YJyQugIJos.png

處理靜默推送通知

新增 didReceiveRemoteNotification 到 UNUserNotificationCenter 的 Delegate

func application(_ application: UIApplication,
                 didReceiveRemoteNotification userInfo: [AnyHashable: Any]) async
  -> UIBackgroundFetchResult {
  // If you are receiving a notification message while your app is in the background,
  // this callback will not be fired till the user taps on the notification launching the application.
  // TODO: Handle data of notification

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  // Messaging.messaging().appDidReceiveMessage(userInfo)

  // Print message ID.
  if let messageID = userInfo[gcmMessageIDKey] {
    print("Message ID: \(messageID)")
  }

  // Print full message.
  print(userInfo)

  return UIBackgroundFetchResult.newData
}

如下圖:
https://ithelp.ithome.com.tw/upload/images/20231008/20151391V5yMnbNP2h.png

你會發現 gcmMessageIDKey 沒有被宣告到,所以我們在 App Delegate 裡新增 gcmMessageIDKey 的變數

let gcmMessageIDKey = "gcm.Message_ID"

如下圖:
https://ithelp.ithome.com.tw/upload/images/20231008/20151391gcHiGaxT4v.png

新增 Background Mode 和 Push Notifications 到Capability

https://ithelp.ithome.com.tw/upload/images/20231008/20151391k1arFR9jNS.png

https://ithelp.ithome.com.tw/upload/images/20231008/20151391lyxcGhuA72.png

https://ithelp.ithome.com.tw/upload/images/20231008/20151391Q66Vejqt3I.png

Background Mode 勾選 Background fetch 、 Remote notifications 、 Background processing

https://ithelp.ithome.com.tw/upload/images/20231008/20151391s4FG3nl7l4.png

好了!到這邊就是所有我們需要在 App 端設置的東西了,明天會教大家怎麼去做 Firebase 那邊的設定喔!


上一篇
鐵人賽 [Day 22] Core ML 教學(7)
下一篇
鐵人賽 [Day 24] FCM(Firebase Cloud Message) 推播教學(2)
系列文
iOS 菜雞的開發日記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言